package com.yunti.business.service.impl;

import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.yunti.business.utils.WordUtil;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.yunti.business.domain.BaseRace;
import com.yunti.business.domain.BaseSchool;
import com.yunti.business.mapper.BaseRaceMapper;
import com.yunti.business.mapper.BaseSchoolMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yunti.business.mapper.BaseStudentMapper;
import com.yunti.business.domain.BaseStudent;
import com.yunti.business.service.IBaseStudentService;

import javax.servlet.http.HttpServletResponse;

/**
 * 学生Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-30
 */
@Service
public class BaseStudentServiceImpl implements IBaseStudentService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private BaseStudentMapper baseStudentMapper;

    @Autowired
    private BaseSchoolMapper baseSchoolMapper;

    @Autowired
    private BaseRaceMapper baseRaceMapper;

    /**
     * 查询学生
     *
     * @param id 学生主键
     * @return 学生
     */
    @Override
    public BaseStudent selectBaseStudentById(Long id) {
        return baseStudentMapper.selectBaseStudentById(id);
    }

    /**
     * 查询学生列表
     *
     * @param baseStudent 学生
     * @return 学生
     */
    @Override
    public List<BaseStudent> selectBaseStudentList(BaseStudent baseStudent) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();
        baseStudent.setRaceId(raceId);
        return baseStudentMapper.selectBaseStudentList(baseStudent);
    }

    /**
     * 新增学生
     *
     * @param baseStudent 学生
     * @return 结果
     */
    @Override
    public int insertBaseStudent(BaseStudent baseStudent) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();
        baseStudent.setRaceId(raceId);
        baseStudent.setCreateTime(LocalDateTime.now());
        return baseStudentMapper.insertBaseStudent(baseStudent);
    }

    /**
     * 修改学生
     *
     * @param baseStudent 学生
     * @return 结果
     */
    @Override
    public int updateBaseStudent(BaseStudent baseStudent) {
        baseStudent.setUpdateTime(LocalDateTime.now());
        return baseStudentMapper.updateBaseStudent(baseStudent);
    }

    /**
     * 批量删除学生
     *
     * @param ids 需要删除的学生主键
     * @return 结果
     */
    @Override
    public int deleteBaseStudentByIds(Long[] ids) {
        return baseStudentMapper.deleteBaseStudentByIds(ids);
    }

    /**
     * 删除学生信息
     *
     * @param id 学生主键
     * @return 结果
     */
    @Override
    public int deleteBaseStudentById(Long id) {
        return baseStudentMapper.deleteBaseStudentById(id);
    }

    @Override
    public String importSstudent(List<BaseStudent> baseStudentList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(baseStudentList) || baseStudentList.size() == 0) {
            throw new ServiceException("导入学校数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();

        for (BaseStudent baseStudent : baseStudentList) {
            try {
                // 验证是否存在这个用户
                BaseStudent oldBaseStudent = baseStudentMapper.selectBaseStudentByStuNO(baseStudent.getStuNo(), baseStudent.getSchoolId());
                baseStudent.setId(oldBaseStudent.getId());
                if (StringUtils.isNull(oldBaseStudent)) {
                    baseStudent.setCreateBy(operName);
                    baseStudent.setCreateTime(LocalDateTime.now());
                    baseStudent.setRaceId(raceId);
                    baseStudentMapper.insertBaseStudent(baseStudent);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + baseStudent.getName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanUtils.copyProperties(baseStudent, oldBaseStudent);
                    oldBaseStudent.setUpdateBy(operName);
                    oldBaseStudent.setUpdateTime(LocalDateTime.now());
                    baseStudentMapper.updateBaseStudent(oldBaseStudent);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + oldBaseStudent.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + baseStudent.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + baseStudent.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String confirmStudent(Long stuId, Integer mode) {
        // 验证是否存在这个学生
        BaseStudent oldBaseStudent = baseStudentMapper.selectBaseStudentById(stuId);
        if (mode == 1) {
            oldBaseStudent.setOneConfirm(1);
            oldBaseStudent.setOneConfirmTime(DateUtils.getNowDate());
        }
        if (mode == 2) {
            oldBaseStudent.setTwoConfirm(1);
            oldBaseStudent.setTwoConfirmTime(DateUtils.getNowDate());
        }
        oldBaseStudent.setUpdateTime(LocalDateTime.now());
        baseStudentMapper.updateBaseStudent(oldBaseStudent);
        return "操作成功";
    }


    @Override
    public String confirmStudentList(ArrayList<Long> stuIdList, Integer mode) {
        for (int i = 0; i < stuIdList.size(); i++) {
            confirmStudent(stuIdList.get(i),mode);
        }
        return "操作成功";
    }

    @Override
    public List<BaseStudent> confirmList(Long schoolId, Integer mode) {
//        BaseStudent baseStudent = new BaseStudent();

//        baseStudent.setSchoolId(schoolId);

//        return baseStudentMapper.selectBaseStudentList(baseStudent);
        LambdaQueryWrapper<BaseStudent> baseStudentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseStudentLambdaQueryWrapper.eq(BaseStudent::getSchoolId, schoolId);
        baseStudentLambdaQueryWrapper.orderByAsc(BaseStudent::getSex);
        if (mode == 1) {
            baseStudentLambdaQueryWrapper.eq(BaseStudent::getOneConfirm, 1);
            baseStudentLambdaQueryWrapper.orderByAsc(BaseStudent::getOneConfirmTime);
        }
        if (mode == 2) {
            baseStudentLambdaQueryWrapper.eq(BaseStudent::getTwoConfirm, 1);
            baseStudentLambdaQueryWrapper.orderByAsc(BaseStudent::getTwoConfirmTime);
        }
        return baseStudentMapper.selectList(baseStudentLambdaQueryWrapper);
    }

    @Override
    public void exportConfirm(BaseStudent baseStudent, HttpServletResponse response) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();

        baseStudent.setOneConfirm(1);

        if (baseStudent.getSchoolId() == null) {
            throw new ServiceException("请先选择学校");
        }

        List<BaseStudent> baseStudentList = confirmList(baseStudent.getSchoolId(),1);
        BaseSchool baseSchool = baseSchoolMapper.selectById(baseStudent.getSchoolId());
        BaseRace baseRace = baseRaceMapper.selectById(raceId);
        for (int i = 0; i < baseStudentList.size(); i++) {
            baseStudentList.get(i).setNo(i + 1 + "");
        }
        WordUtil.output(response, baseStudentList, baseRace.getName(), baseSchool.getName());
    }

}
